﻿import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { EntityDtoOfInt64,  UserServiceProxy } from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
//import { CreateOrEditCodeBaseModalComponent } from './create-or-edit-code-base-modal.component';
//import { LogCodeBaseModalComponent } from './log-code-base-modal.component';
import { HttpClient } from '@angular/common/http';
import { FileUpload } from 'primeng/fileupload';
import { finalize } from 'rxjs/operators';
import { StandardPartsDetailDto,StandardPartsFeatureDto ,ImportAllotDto,UsingFormServiceProxy} from '@shared/service-proxies/service-proxies';
import { StandardPartsDetailServiceProxy,StandardDetailType} from '@shared/service-proxies/service-proxies';
import { FetchImportAbnormalTabComponent } from './fetch-import-abnormal_tab.component';
import { FetchImportRequirementGetEditComponent } from './fetch-import-requirement-get_edit.component'
import { FetchImportRequirementGetAllEditComponent } from './fetch-import-requirement-getall_edit.component'
import { Tab } from './tab.model';

@Component({
    templateUrl: './fetch-import.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./fetch-import.component.less'],
    animations: [appModuleAnimation()]
})
export class FetchImportComponent extends AppComponentBase {

    //@ViewChild('createOrEditCodeBaseModal') createOrEditCodeBaseModal: CreateOrEditCodeBaseModalComponent;
    //@ViewChild('logCodeBaseModal') logCodeBaseModal: LogCodeBaseModalComponent;
    @ViewChild('fetchImportRequirementGetEditComponent') fetchImportRequirementGetEditComponent: FetchImportRequirementGetEditComponent;
    @ViewChild('fetchImportRequirementGetAllEditComponent') fetchImportRequirementGetAllEditComponent: FetchImportRequirementGetAllEditComponent;
    @ViewChild('fetchImportAbnormalTabComponent') fetchImportAbnormalTabComponent: FetchImportAbnormalTabComponent;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('ExcelFileUpload') excelFileUpload: FileUpload;

    uploadUrl: string;

    //Filters
    advancedFiltersAreShown = false;
    filterText = '';
    selectedPermission = '';
    role = '';
    onlyLockedUsers = false;
    tabs: Array<Tab>;


    constructor(
        injector: Injector,
        private _userServiceProxy: UserServiceProxy,
        private _standardPartsDetailServiceProxy: StandardPartsDetailServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _activatedRoute: ActivatedRoute,
        private _usingFormServiceProxy: UsingFormServiceProxy,
        private _httpClient: HttpClient
    ) {
        super(injector);
        this.filterText = this._activatedRoute.snapshot.queryParams['filterText'] || '';
        this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/StandardParts/ImportAllotExcel';
        this.tabs = new Array();
        this.addTab();
    }
    addTab(): void {
        let tab: Tab = new Tab("不满足需求");
        tab.index = this.tabs.length;
        tab.active = true;
        this.tabs.push(tab);
    }
    
    getStandardPartsDetailIsTemperingText(value): string {
        if (value) {
            return "是";
        } else {
            return "否";
        }
    }
    getStandardParts(event?: LazyLoadEvent){
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
    }
    getCodeBase(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._standardPartsDetailServiceProxy.getAllDetail(
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event))
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
    getStandarType(standardType:string):string{
        return StandardDetailType[standardType];
    }

    unlockUser(record): void {
        this._userServiceProxy.unlockUser(new EntityDtoOfInt64({ id: record.id })).subscribe(() => {
            this.notify.success(this.l('UnlockedTheUser', record.userName));
        });
    }

    getRolesAsString(roles): string {
        let roleNames = '';

        for (let j = 0; j < roles.length; j++) {
            if (roleNames.length) {
                roleNames = roleNames + ', ';
            }

            roleNames = roleNames + roles[j].roleName;
        }

        return roleNames;
    }

    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    exportToExcel(): void {
        this._userServiceProxy.getUsersToExcel(
            this.filterText,
            this.permission ? this.selectedPermission : undefined,
            this.role !== '' ? parseInt(this.role) : undefined,
            this.onlyLockedUsers,
            this.primengTableHelper.getSorting(this.dataTable))
            .subscribe(result => {
                this._fileDownloadService.downloadTempFile(result);
            });
    }

    createUser(): void {    
        //this.createOrEditCodeBaseModal.show();
    }
    logCodeBase(): void {
        //this.logCodeBaseModal.show();
    }
    uploadExcel(data: { files: File }): void {
        const formData: FormData = new FormData();
        const file = data.files[0];
        formData.append('file', file, file.name);

        this._httpClient
            .post<any>(this.uploadUrl, formData)
            .pipe(finalize(() => this.excelFileUpload.clear()))
            .subscribe(result => {
                this.segData(result.result);
            });
    }
    segData( records):void{
        if(!records || records.length== 0){
            return;
        }
        let iad:ImportAllotDto;
        let list:Array<object>;
        let params :Array<ImportAllotDto>= new Array();
        for (var i = 0; i < records.length; i++) {
            params.push(records[i]);
        }
        this._usingFormServiceProxy.filtrateRequirement(params)
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                if(result.usableAllotDtos){
                    this.primengTableHelper.totalRecordsCount = result.usableAllotDtos.length;
                    this.primengTableHelper.records = result.usableAllotDtos;
                }

                if(result.unusableAllotDtos){
                    this.fetchImportAbnormalTabComponent.primengTableHelper.totalRecordsCount = result.unusableAllotDtos.length;
                    this.fetchImportAbnormalTabComponent.primengTableHelper.records = result.unusableAllotDtos;
                }

            });
    }
    createOrEditRequirementPackage(importAllotDto: ImportAllotDto): void {
        this.fetchImportRequirementGetEditComponent.show(importAllotDto,this.primengTableHelper.records);
    }
    requirementGetAll():void{
        this.fetchImportRequirementGetAllEditComponent.show(this.primengTableHelper.records);
    }
    onUploadExcelError(): void {
        this.notify.error("上传失败");
    }

    deleteCodeBase(standardPartsDetail: StandardPartsDetailDto): void {

        this.message.confirm(
            '编码库将被删除',
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._standardPartsDetailServiceProxy.deleteDetail(standardPartsDetail.id)
                    .pipe(finalize(() => { this.getCodeBase();}))
                    .subscribe(() => {
                        this.notify.info(this.l('DeletedSuccessfully'));
                    });
                }
            }
        );
    }
    getRequirementPackages($event){

    }
}
